package co.yixiang.hw.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import co.yixiang.hw.domain.SupplierGoodsSku;
import co.yixiang.hw.domain.SupplierGoodsSkuLog;
import co.yixiang.hw.repository.SupplierGoodsSkuLogRepository;
import co.yixiang.hw.repository.SupplierGoodsSkuRepository;
import co.yixiang.hw.service.SupplierGoodsSkuService;
import co.yixiang.hw.service.dto.SupplierGoodsSkuDto;
import co.yixiang.hw.service.dto.SupplierGoodsSkuQueryCriteria;
import co.yixiang.hw.service.mapper.SupplierGoodsSkuMapper;
import co.yixiang.utils.*;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.Inet4Address;
import java.util.*;


/**
* @author Walert
* @date 2021-03-22
*/
@Service
//@CacheConfig(cacheNames = "supplierGoodsSku")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SupplierGoodsSkuServiceImpl implements SupplierGoodsSkuService {

    @Resource
    private SupplierGoodsSkuRepository supplierGoodsSkuRepository;
    @Resource
    private SupplierGoodsSkuMapper supplierGoodsSkuMapper;
    @Resource
    private SupplierGoodsSkuLogRepository goodsSkuLogRepository;


    @Override
    //@Cacheable
    public Map<String,Object> queryAll(Integer level, SupplierGoodsSkuQueryCriteria criteria, Pageable pageable){
        criteria.setIsDel(0);
        criteria.setStatus(1);
        Page<SupplierGoodsSku> page = supplierGoodsSkuRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        List<SupplierGoodsSku> list = page.getContent();
        for (SupplierGoodsSku sku : list) {
            this.formatPrice(level, sku);
        }
        return PageUtil.toPageHadTotalPage(page.getContent(),page.getTotalElements(),page.getTotalPages());
    }

    private void formatPrice(Integer level, SupplierGoodsSku sku) {

        if(level == 0){
            sku.setFirstSalePrice(0L);
            sku.setFirstSourcePrice(0L);
//                sku.setSalePrice(0L);
            sku.setSourcePrice(0L);
            sku.setSecondSalePrice(0L);
            sku.setSecondSourcePrice(0L);
            sku.setThridSalePrice(0L);
            sku.setThridSourcePrice(0L);
        }else if(level == 1){
//                sku.setFirstSalePrice(0L);
//                sku.setFirstSourcePrice(0L);
            sku.setSalePrice(0L);
            sku.setSourcePrice(0L);
            sku.setSecondSalePrice(0L);
            sku.setSecondSourcePrice(0L);
            sku.setThridSalePrice(0L);
            sku.setThridSourcePrice(0L);
        }else if(level == 2){
            sku.setFirstSalePrice(0L);
            sku.setFirstSourcePrice(0L);
            sku.setSalePrice(0L);
            sku.setSourcePrice(0L);
//                sku.setSecondSalePrice(0L);
//                sku.setSecondSourcePrice(0L);
            sku.setThridSalePrice(0L);
            sku.setThridSourcePrice(0L);
        }else if(level == 3){
            sku.setFirstSalePrice(0L);
            sku.setFirstSourcePrice(0L);
            sku.setSalePrice(0L);
            sku.setSourcePrice(0L);
            sku.setSecondSalePrice(0L);
            sku.setSecondSourcePrice(0L);
//                sku.setThridSalePrice(0L);
//                sku.setThridSourcePrice(0L);
        }else if(level == 4){
            sku.setFirstSalePrice(0L);
            sku.setFirstSourcePrice(0L);
//                sku.setSalePrice(0L);
//                sku.setSourcePrice(0L);
            sku.setSecondSalePrice(0L);
            sku.setSecondSourcePrice(0L);
            sku.setThridSalePrice(0L);
            sku.setThridSourcePrice(0L);
        }
    }

    public Map<String,Object> queryAll(SupplierGoodsSkuQueryCriteria criteria, Pageable pageable){
        return this.queryAll(0,criteria,pageable);
    }


    @Override
    //@Cacheable
    public List<SupplierGoodsSkuDto> queryAll(SupplierGoodsSkuQueryCriteria criteria){
        return supplierGoodsSkuMapper.toDto(supplierGoodsSkuRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    //@Cacheable(key = "#p0")
    public SupplierGoodsSkuDto findById(Integer level,Long id) {
        SupplierGoodsSku supplierGoodsSku = supplierGoodsSkuRepository.findById(id).orElseGet(SupplierGoodsSku::new);
        ValidationUtil.isNull(supplierGoodsSku.getId(),"SupplierGoodsSku","id",id);
        this.formatPrice(level,supplierGoodsSku);
        return supplierGoodsSkuMapper.toDto(supplierGoodsSku);
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public SupplierGoodsSkuDto create(SupplierGoodsSku resources) {
        SupplierGoodsSku goodsSku = supplierGoodsSkuRepository.save(resources);
        this.saveSkuLog(goodsSku);
        return supplierGoodsSkuMapper.toDto(goodsSku);
    }

    @Override
    //@CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(SupplierGoodsSku resources) {
        SupplierGoodsSku supplierGoodsSku = supplierGoodsSkuRepository.findById(resources.getId()).orElseGet(SupplierGoodsSku::new);
        ValidationUtil.isNull(supplierGoodsSku.getId(), "SupplierGoodsSku", "id", resources.getId());
        supplierGoodsSku.copy(resources);
        supplierGoodsSkuRepository.save(supplierGoodsSku);
        if (supplierGoodsSku.getIsDel() == 0) {
            this.saveSkuLog(supplierGoodsSku);
        }
    }

    private void saveSkuLog(SupplierGoodsSku goodsSku){
        SupplierGoodsSkuLog goodsSkuLog = new SupplierGoodsSkuLog();
        long timeMillis = System.currentTimeMillis();
        goodsSkuLog.setSkuId(goodsSku.getId());
        goodsSkuLog.setChangeTime(timeMillis);
        goodsSkuLog.setAddTime(goodsSku.getAddTime());
        goodsSkuLog.setEffeTime(goodsSku.getEffeTime());
        goodsSkuLog.setOutTime(goodsSku.getOutTime());
        goodsSkuLog.setFirstSourcePrice(goodsSku.getFirstSourcePrice());
        goodsSkuLog.setFirstSalePrice(goodsSku.getFirstSalePrice());
        goodsSkuLog.setSecondSourcePrice(goodsSku.getSecondSourcePrice());
        goodsSkuLog.setSecondSalePrice(goodsSku.getSecondSalePrice());
        goodsSkuLog.setThridSourcePrice(goodsSku.getThridSourcePrice());
        goodsSkuLog.setThridSalePrice(goodsSku.getThridSalePrice());
        goodsSkuLog.setSourcePrice(goodsSku.getSourcePrice());
        goodsSkuLog.setSalePrice(goodsSku.getSalePrice());
        goodsSkuLog.setCreateTime(timeMillis);
        goodsSkuLog.setCreateUser(SecurityUtils.getUsername());
        goodsSkuLog.setIsDel(0);
        goodsSkuLogRepository.save(goodsSkuLog);
    }

    @Override
    //@CacheEvict(allEntries = true)
    public void deleteAll(Long[] ids) {
        SupplierGoodsSku updateObj = new SupplierGoodsSku();
        updateObj.setIsDel(1);
        updateObj.setUpdateTime(System.currentTimeMillis());
        updateObj.setUpdateUser(SecurityUtils.getUsername());
        for (Long id : ids) {
            updateObj.setId(id);
            this.update(updateObj);
        }
    }

    @Override
    public void download(List<SupplierGoodsSkuDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SupplierGoodsSkuDto supplierGoodsSku : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("商品名", supplierGoodsSku.getName());
            map.put("商品编码", supplierGoodsSku.getCode());
            map.put("状态 0：草稿 1：发布", supplierGoodsSku.getStatus());
            map.put("规格", supplierGoodsSku.getSpac());
            map.put("商品图片", supplierGoodsSku.getSkuImg());
            map.put("轮播图片", supplierGoodsSku.getHeadImgs());
            map.put("物料下载地址", supplierGoodsSku.getMaterial());
            map.put("上市时间", supplierGoodsSku.getAddTime());
            map.put("退市时间", supplierGoodsSku.getOutTime());
            map.put("价格有效时间", supplierGoodsSku.getEffeTime());
            map.put("一级供应商供货价(分)", supplierGoodsSku.getFirstSourcePrice());
            map.put("一级供应商建议售价(分)", supplierGoodsSku.getFirstSalePrice());
            map.put("二级供应商供货价(分)", supplierGoodsSku.getSecondSourcePrice());
            map.put("二级供应商建议售价(分)", supplierGoodsSku.getSecondSalePrice());
            map.put("三级供应商供货价(分)", supplierGoodsSku.getThridSourcePrice());
            map.put("三级供应商建议售价(分)", supplierGoodsSku.getThridSalePrice());
            map.put("零售供货价(分)", supplierGoodsSku.getSourcePrice());
            map.put("零售建议售价(分)", supplierGoodsSku.getSalePrice());
            map.put("是否删除 0：否 1：是", supplierGoodsSku.getIsDel());
            map.put("创建时间", supplierGoodsSku.getCreateTime());
            map.put("创建用户", supplierGoodsSku.getCreateUser());
            map.put("更新时间", supplierGoodsSku.getUpdateTime());
            map.put("更新用户", supplierGoodsSku.getUpdateUser());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public  Map<String,Object> getGoodsSkuListByTypePage(Integer type, Integer level, Integer pageNo, Integer pageSize) {
        Map<String, Object> result = null;
        SupplierGoodsSkuQueryCriteria queryCriteria = new SupplierGoodsSkuQueryCriteria();
        if(type == 0){
            Long[] dateTimes = this.getCurrentQuarterDateTime();
            queryCriteria.setBeginTime(dateTimes[0]);
            queryCriteria.setEndTime(dateTimes[1]);
        }else if(type == 1){
            DateTime dateTime = DateUtil.nextMonth();
            DateTime beginDateTime = DateUtil.beginOfMonth(dateTime);
            DateTime endDateTime = DateUtil.endOfMonth(dateTime);
            queryCriteria.setBeginTime(beginDateTime.getTime());
            queryCriteria.setEndTime(endDateTime.getTime());
        }else if(type == 2){

        }
        Pageable pageable = PageRequest.of(pageNo,pageSize,Sort.by("createTime").descending());
        result = this.queryAll(level, queryCriteria, pageable);
        return result;
    }

    private Long [] getCurrentQuarterDateTime(){
        DateTime beginDateTime = DateUtil.beginOfQuarter(new Date());
        DateTime endDateTime = DateUtil.endOfQuarter(new Date());
        Long [] dateTimes = new Long[]{beginDateTime.getTime(),endDateTime.getTime()};
        return dateTimes;
    }
}
